<template>
  <!--右键菜单组件-->
  <div v-if="visible && menuList.length" ref="menu" class="content-menu-com" :style="positionObj">
    <div
      v-for="(item, index) in menuList"
      :key="index"
      class="com-item"
      @mousedown.stop="e => handleClick(e, index)"
    >
      {{ item.label }}
    </div>
  </div>
</template>

<script>
import eventBus from '@veditor/eventBus';

export default {
  name: 'ContextMenu',
  model: {
    prop: 'visible',
    event: 'update',
  },
  props: {
    position: {
      type: Object,
      required: true,
    },
    menuList: {
      type: Array,
      required: true,
    },
    visible: {
      type: Boolean,
      required: true,
    },
    index: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      positionObj: {
        left: '-1000px',
        top: '-1000px',
      },
    };
  },
  computed: {
    canShow() {
      return this.visible && this.menuList.length;
    },
  },
  watch: {
    canShow(value) {
      if (value) {
        this.$nextTick(() => {
          const currentHeight = this.$refs.menu?.clientHeight ?? 0;
          this.positionObj = {
            left: `${this.position.left}px`,
            top: `${this.position.top - currentHeight}px`,
          };
        });
      }
    },
  },
  mounted() {
    document.addEventListener('contextmenu', this.closeContextMenu, { capture: true });
    document.addEventListener('mousedown', this.closeContextMenu);
    eventBus.$on('lineItemMouseDown', this.closeContextMenu);
  },
  beforeDestroy() {
    document.removeEventListener('contextmenu', this.closeContextMenu);
    document.removeEventListener('mousedown', this.closeContextMenu);
  },
  methods: {
    // 处理点击事件
    handleClick(e, index) {
      e.stopPropagation();
      e.preventDefault();
      this.$emit('update', false);
      this.$emit('click', this.index, this.menuList[index].value);
    },
    // 关闭菜单
    closeContextMenu() {
      this.$emit('update', false);
    },
  },
};
</script>

<style lang="stylus" scoped>
.content-menu-com
  padding 2px 8px 2px 12px
  position fixed
  background #282828
  color #bbb
  border-radius 8px
  width 122px
  box-shadow 0 4px 10px rgb(0 0 0 / 20%)
  z-index 11
  .com-item
    width 100px
    height 30px
    line-height 30px
    cursor pointer
    &:hover
      color #f13131
</style>
